package com.lv.suyiyong.hfr.fragment

import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.tabs.TabLayoutMediator
import com.lv.common.adapter.ViewPager2Adapter
import com.lv.common.base.BaseFragment
import com.lv.common.ktx.setSelectedTabIndicatorFixWidth
import com.lv.common.utils.Constants
import com.lv.service.room.company.CompanyItemBean
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.FragmentCompanyProductBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob

/**
 * 作者： ygx
 * 创建日期：2023/3/10 3:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述： NewTemplate 1 公司首页 黑色模板
 */
class CompanyProductFragment : BaseFragment(), OnClickListener {
    private val mTabs: MutableList<String> =
        mutableListOf<String>("全部", "产品分类", "推荐", "新品")
    private val mFragments = mutableListOf<Fragment>()
    private var mCpyid: String = ""
    private var mCurrentTab: Int = 0
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val parmasMap = mutableMapOf<String, String>()
    private var mCompanyInfo: CompanyItemBean? = null

    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mBinding: FragmentCompanyProductBinding? = null
    override fun getLayoutRes() = R.layout.fragment_company_product

    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentCompanyProductBinding.bind(view).apply {
        }
        return mBinding!!
    }


    override fun initConfig() {
        super.initConfig()
    }


    private fun initFragment() {
        mFragments.clear()
        mFragments.add(CompanyProductChildFragment.newInstance(mCpyid, "0"))
        mFragments.add(CompanyCategoryLRFragment.newInstance(mCpyid))
        mFragments.add(CompanyProductChildVFragment.newInstance(mCpyid, "2"))
        mFragments.add(CompanyProductChildVFragment.newInstance(mCpyid, "3"))
        val mTabAdapter = ViewPager2Adapter(
            childFragmentManager, lifecycle, mTabs,
            object : ViewPager2Adapter.TabPagerListener {
                override fun getFragment(position: Int): Fragment {
                    return mFragments[position]
                }

            }
        )
        mBinding?.viewPager?.adapter = mTabAdapter
        TabLayoutMediator(mBinding?.tabLayout!!, mBinding?.viewPager!!) { tab, position ->
            tab.text = mTabs[position]
        }.attach()

        mBinding?.viewPager?.offscreenPageLimit = mTabs.size
        mBinding?.tabLayout?.setSelectedTabIndicatorFixWidth(SizeUtils.dp2px(19.0f).toFloat())
        mBinding?.tabLayout?.addOnTabSelectedListener(YgxToolsKt.setSelectedBoldTab())

        val selecTab = mTabs[mCurrentTab]
        val spannedString = YgxToolsKt.setTextSpan(selecTab, Typeface.BOLD)
        mBinding?.tabLayout?.getTabAt(mCurrentTab)?.text = spannedString
        setCurrentFragment(mCurrentTab)
    }

    fun setCurrentFragment(current: Int) {
        mBinding?.viewPager?.currentItem = current
    }


    override fun initData() {
        super.initData()
        arguments?.let {
            mCompanyInfo = it.getParcelable<CompanyItemBean>("companyBean")
        }
        mCpyid = mCompanyInfo?.id ?: ""
        initFragment()
//        UserDbHelper.getLiveUserInfo(requireContext()).observeKt {
//            isLogin = !it?.id.isNullOrEmpty()
//            mUserInfo = it
//        }
//        initUI()
//        initAdapter()
//        mCpLogo?.LoadSrc(mCompanyInfo?.image)
//        mIvGC?.LoadSrc(Constants.FACTORY_TAG)
//        mIvPP?.LoadSrc(Constants.BRAND_TAG)
////        mLLMini?.visibility =
////            if (mCompanyInfo?.wxappid.isNullOrEmpty()) View.GONE else View.VISIBLE
//        mEwms.clear()
//        val ewms = mCompanyInfo?.ewms
//        ewms?.forEach { url ->
//            mEwms.add(url.ewm ?: "")
//        }
////        mLlWeiChat?.visibility =
////            if (ewms.isNullOrEmpty()) View.GONE else View.VISIBLE
//        mCpyid = mCompanyInfo?.id ?: ""
//        mTxaccid = mCompanyInfo?.txaccid ?: ""
//        mCompanyCpName = mCompanyInfo?.name ?: ""
//        findCompanyAccess()
//        findComAttached()
//        mIsFoucs = mCompanyInfo?.status == "1"//0 未关注 1 关注
//        mTvXinyong?.text = "信用分：${mCompanyInfo?.creditValue}"
//
//        mTvCpname?.text = mCompanyCpName
//        mTvZizhiDec?.text = "统一社会信用代码：${mCompanyInfo?.identification}"
//        mTvVist?.text = "${mCompanyInfo?.access}".zero()
//        mTvFans?.text = "${mCompanyInfo?.attentionnum}".zero()
//        mTvCir?.text = "${mCompanyInfo?.publishnum}".zero()
//        mTvCommit?.text = "${mCompanyInfo?.callnum}".zero()
//        val catption = mCompanyInfo?.caption ?: "这个用户很懒，什么都没有留下~"
//        mTvDes?.text = catption
//        mTvDes?.post {
//            val (textOverflowing, num) = mTvDes!!.isTextOverflowing(3)
//            if (textOverflowing) {
//                mShowCompanyDecPop = true
//                mIvDesArrow?.visibility = View.VISIBLE
//                val substring = catption.substring(0, num - 5)
//                mTvDes?.text = "${substring}…"
//            } else {
//                mShowCompanyDecPop = false
//                mIvDesArrow?.visibility = View.GONE
//            }
////            LogUtils.e(textOverflowing.toString())
//        }
//
////        mTvDesExpend?.setText(mCompanyInfo?.caption ?: "这个用户很懒，什么都没有留下~")
//        mTvTime?.text =
//            TimeUtil.getDateTimeString(mCompanyInfo?.created ?: 0, "yyyy年MM月dd日")
//
////        mTvAddressDec?.text = mAddress
//        mSiteBeans.clear()
//        val site = mCompanyInfo?.site
//        if (site.isNullOrEmpty()) {
//            mAddress = mCompanyInfo?.prefecture ?: ""
//            if (mAddress.isNotEmpty()) {
//                mAddress =
//                    "${mCompanyInfo?.province}${mCompanyInfo?.city}${mCompanyInfo?.area}${mCompanyInfo?.prefecture}${mCompanyInfo?.address}"
//            } else {
//                mAddress = "${mCompanyInfo?.address}"
//            }
//            mSiteBeans.add(AddressDetailsBean(mAddress, "", "", "", "", ""))
//        } else {
//            mSiteBeans.addAll(site)
//        }
//        mAddressAdapter?.notifyDataSetChanged()
//        setFlowData()
//        initPhones()
//
//        //0  普通  1 银牌  2 金牌
//        mSpecially = mCompanyInfo?.isspecially ?: "0"
//        when (mSpecially) {
//            "2" -> {
//                mTvCpname?.setTextColor(Color.parseColor("#FFDC96"))
//                mIvGold?.visibility = View.VISIBLE
//                mTvGold?.visibility = View.VISIBLE
//                mTvXinyong?.setTextColor(Color.parseColor("#999999"))
////                mBinding?.ivTag?.LoadSrc(com.lv.common.R.drawable.icon_nomal_tag)
//            }
//
//            else -> {
//                mTvCpname?.setTextColor(Color.parseColor("#242424"))
//                mIvGold?.visibility = View.GONE
//                mTvGold?.visibility = View.GONE
//                mTvXinyong?.setTextColor(Color.parseColor("#242424"))
//
//            }
//        }
//        val brand = mCompanyInfo?.brand ?: "0"
//        val factory = mCompanyInfo?.factory ?: "0"
//        mIvGC?.visibility = if (factory == "1") View.VISIBLE else View.GONE
//        mIvPP?.visibility = if (brand == "1") View.VISIBLE else View.GONE
//        mTvRZ?.visibility = if (mSpecially == "1") View.VISIBLE else View.GONE
//        if (factory == "1" || brand == "1" || mSpecially == "1") {
//            mViewHSub?.visibility = View.VISIBLE
//        } else {
//            mViewHSub?.visibility = View.GONE
//        }
//        initFoucs()
//        val displayFac = mCompanyInfo?.displayFac
//        displayFac?.let {
//            var picCount = 0
//            var videoCount = 0
//            displayFac.indices.forEach { i ->
//                val type = displayFac[i].type
//                var mType = ViewTypeBean.PIC_TYPE
//                if (type == "1") {
//                    mType = ViewTypeBean.VEDIO_TYPE
//                    videoCount++
//                } else {
//                    picCount++
//                }
//                mBannerBeans.add(ViewTypeBean(mType, displayFac[i]))
//            }
//            if (videoCount > 0) {
//                mBanner?.isAutoLoop(false)
//            } else {
//                mBanner?.isAutoLoop(true)
//                mBanner?.setLoopTime(1500)
//            }
//        }
//
//        mBannerAdapter = BannerMediaNoBroderAdapter(mBannerBeans)
//        mBanner?.adapter = mBannerAdapter
//        mBanner?.addOnPageChangeListener(object : OnPageChangeListener {
//            override fun onPageScrolled(
//                position: Int,
//                positionOffset: Float,
//                positionOffsetPixels: Int
//            ) {
//
//            }
//
//            override fun onPageSelected(position: Int) {
//                if (mBannerBeans[position].type == ViewTypeBean.VEDIO_TYPE) {
//                    startVideo(position)
//                } else {
//                    stopVideo()
//                }
//                inTentPosition = position
//
//            }
//
//            override fun onPageScrollStateChanged(state: Int) {
//            }
//        })
////                ?.setOnBannerListener(OnBannerListener<ViewTypeBean> { data, position ->
////                    val json = GsonUtils.toJson(mBannerBeans)
////                    ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
////                        .withInt("position", position)
////                        .withString("data", json)
////                        .navigation()
////                })
//        mBannerAdapter?.onViewClickListener = OnPositionTListener { position, data ->
//            inTentAction = true
////            var mP = position - 1
//////            if (mBannerBeans[0].type == 1) {
//////                mP = position
//////            } else {
//////                mP = position - 1
//////            }
//            val json = GsonUtils.toJson(mBannerBeans)
//            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
//                .withInt("position", position - 1)
//                .withString("data", json)
//                .navigation()
//        }
//        mFactoryAdapter?.notifyDataSetChanged()
//        initCertification()

    }


    override fun initEvents() {
        super.initEvents()
        rigestEventBus()
    }


    private fun rigestEventBus() {
//        LiveEventBus.get(CompanyEvent::class.java).observe(this) { event ->
//            if (event == null) {
//                return@observe
//            }
//            mCompanyInfo = event.companyItemBean
//            mIsFoucs = mCompanyInfo?.status == "1"//0 未关注 1 关注
//            initFoucs()

//        }

        //关注 点赞 评论 收藏
//        LiveEventBus.get(CirStatePageEvent::class.java).observe(this) { event ->
//            if (event == null) {
//                return@observe
//            }
//
//            when (event.tag) {
//                CirStateEventEnum.FOUCS -> {
//                    val cpyid = event.cpyid
//                    val id = mCompanyInfo?.id
//                    if (id == cpyid) {
//                        mIsFoucs = event.hasFocus == "1"
//                        initFoucs()
//                    }
//
//                }
//            }
//
//        }

    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back_black, R.id.iv_back_white -> {
                activity?.finish()
            }


        }
    }


    override fun onResume() {
        super.onResume()
        LogUtils.e("aaaaaaaaaaaaaaaaaa--onResume")

    }


    override fun onDestroy() {
        super.onDestroy()
    }


    companion object {
        fun newInstance(companyBean: CompanyItemBean?): CompanyProductFragment {
            val args = Bundle()
            args.putParcelable("companyBean", companyBean)

            val fragment = CompanyProductFragment()
            fragment.arguments = args
            return fragment
        }
    }

}